﻿<% @LANGUAGE="VBSCRIPT" CODEPAGE="65001" %>
<%
Option Explicit

Session.CodePage = 65001

Const SCHOOLNAME_REQUIRED = 1
Const LEADERNAME_REQUIRED = 2
Const LEADERTEL_REQUIRED = 4
Const INVALID_LEADEREMAIL = 5
Const LEADERGRADE_REQUIRED = 6
Const INVALID_SUPERVISORTEL = 7
Const INVALID_SUPERVISOREMAIL = 8
Const INVALID_LEADERTEL = 9
Const MEMBERCONTACT_REQUIRED = 1010
Const MEMBERGRADE_REQUIRED = 1020
Const INVALID_MEMBEREMAIL = 1030
Const INVALID_MEMBERTEL = 1040
Const BACK_BUTTON = 200
Const SUCCESS_MSG = 100
Const SUCCESS_SUBJECT = 101
Const UNKNOWN_ERROR = 999
Const EMAIL_SERVER = "192.168.215.186"
'Const EMAIL_SERVER = "smtp.macau.ctm.net"

Function IIf(condition,value1,value2)
	If condition Then IIf = value1 Else IIf = value2
End Function


Function IsValidEmail(myEmail)
  dim regEx
  
  IsValidEmail = True
  set regEx = New RegExp
  
  regEx.IgnoreCase = True
  
  regEx.Pattern = "^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$"
  IsValidEmail = regEx.Test(myEmail)
End Function

Function IsValidDate(DateStr)
  On Error Resume Next
  Dim DateParts
  Dim MonthPart, DayPart, YearPart
  IsDate = False
  DateParts = split(DateStr, "/")
  if IsArray(DateParts) then 
   if UBound(DateParts)=2 then
      DayPart=CInt(DateParts(0))
      MonthPart=CInt(DateParts(1))
      YearPart=CInt(DateParts(2))
      IsDate=(DayPart>=1 and DayPart<=31) and (Monthpart>=1) and (MonthPart<=12) 
   end if
  end if
End Function

Function IsValidFutureDate(DateStr)
  On Error Resume Next
  Dim DateParts
  Dim MonthPart, DayPart, YearPart
  IsValidFutureDate = False
  DateParts = split(DateStr, "/")
  if IsArray(DateParts) then 
   if UBound(DateParts)=2 then
      DayPart=CInt(DateParts(0))
      MonthPart=CInt(DateParts(1))
      YearPart=CInt(DateParts(2))
      if (DayPart>=1 and DayPart<=31) and (MonthPart>=1) and (MonthPart<=12) then
	IsValidFutureDate=DateSerial(YearPart, MonthPart, DayPart)>=Date
      end if 
   end if
  end if
End Function

Function IsValidTime(TimeStr)
  Dim TimeParts
  Dim HourPart, MinPart

  IsValidTime = False

  TimeParts = split(TimeStr, ":")
  if UBound(TimeParts)=1 then
     HourPart = CInt(TimeParts(0))
     MinPart = CInt(TimeParts(1))
     IsValidTime=(HourPart>=0) and (HourPart<=23) and (MinPart>=0) and (MinPart<=59)
  end if
End Function

Function IsValidInteger(number)
  dim regex
  set regEx = New RegExp
  
  regEx.IgnoreCase = True
  
  regEx.Pattern = "^[0-9]+$"
  IsValidInteger = regEx.Test(number)
End Function

Function IsValidPhone(number)
  dim regex
  set regEx = New RegExp
  
  regEx.IgnoreCase = True
  
  regEx.Pattern = "^((28[0-9]{6})|((6|8)[0-9]{7})).*$"
  IsValidPhone = regEx.Test(number)
End Function

Function GetErrorMessage(Language, MsgNum)
  GetErrorMessage = ""  
  select case MsgNum
    case SCHOOLNAME_REQUIRED
       select case Language
         case "eng" 
	          GetErrorMessage = "Please fill in the school name"
         case "chi"
            GetErrorMessage = "請填寫學校名稱"
         case "por"
            GetErrorMessage = "Por favor preencher o nome da escola"
       end select
    case LEADERNAME_REQUIRED
       select case Language
         case "eng" 
	           GetErrorMessage = "Please fill in the Name of the leader"
         case "chi"
            GetErrorMessage = "請填寫組長姓名"
         case "por"
            GetErrorMessage = "Por favor preencher o nome do l&iacute;der"
       end select
    case LEADERTEL_REQUIRED
       select case Language
         case "eng" 
	           GetErrorMessage = "Please fill in the contact phone of the leader"
         case "chi"
            GetErrorMessage = "請填寫組長聯絡電話"
         case "por"
            GetErrorMessage = "Por favor preencher o n&uacute;mero do telefone do l&iacute;der"
       end select
    case INVALID_LEADEREMAIL
       select case Language
         case "eng" 
	          GetErrorMessage = "Please fill in a correct email address of the leader"
         case "chi"
            GetErrorMessage = "請填寫正確的組長電郵地址"
         case "por"
            GetErrorMessage = "Por favor preencher o endere&ccedil;o de e-mail correcto do l&iacute;der"
       end select
   case INVALID_LEADERTEL
       select case Language
         case "eng" 
	        GetErrorMessage = "Please fill in a correct contact phone number of the leader"
         case "chi"
            GetErrorMessage = "請填寫正確的組長的電話號碼"
         case "por"
            GetErrorMessage = "Por favor preencher o n&uacute;mero de telefone correcto do l&iacute;der"
       end select       
   case INVALID_SUPERVISORTEL
       select case Language
         case "eng" 
	        GetErrorMessage = "Please fill in a correct contact phone number of the supervisor"
         case "chi"
            GetErrorMessage = "請填寫正確的指導老師的電話號碼"
         case "por"
            GetErrorMessage = "Por favor preencher o n&uacute;mero de telefone correcto do professor supervisor"
       end select       
    case INVALID_SUPERVISOREMAIL
       select case Language
         case "eng" 
	      GetErrorMessage = "Please fill in a correct email address of the supervisor"
         case "chi"
            GetErrorMessage = "請填寫正確的指導老師的電郵地址"
         case "por"
            GetErrorMessage = "Por favor preencher o endere&ccedil;o de e-mail correcto do professor supervisor"
       end select
    case LEADERGRADE_REQUIRED
       select case Language
         case "eng" 
	    GetErrorMessage = "Please fill in the grade of the leader"
         case "chi"
            GetErrorMessage = "請填寫組長年級"
         case "por"
            GetErrorMessage = "Por favor preencher o grau de escolaridade do l&iacute;der"
       end select
    case SUCCESS_MSG
       select case Language
         case "eng" 
	    GetErrorMessage = "Thanks for your application. Our staff will review the application form within two working days and will contact you for further arrangement soon. If you do not receive any confirmation call from us, please call 28718063 or 28718570 for assistance."
         case "chi"
            GetErrorMessage = "<big>多謝您參加比賽。我們的工作人員將會處理這申請表，<font color='red'>並會在2個工作天內與您聯絡</font>。若您在2個工作天後仍然收不到確認報名資料的信息，請致電28718063或28718057查詢情況。</big>"
         case "por"
            GetErrorMessage = "Obrigado pela sua participa&ccedil;&atilde;o no Concurso. A sua Ficha de Inscri&ccedil;&atilde;o vai ser processada e vamos contact&aacute;-lo em breve para confirmar os seus dados. Se n&atilde;o receber nenhuma confirma&ccedil;&atilde;o dentro de 2 dias &uacute;teis, por favor contactar por telefone 28718063 ou 28718570 para assist&ecirc;ncia."
       end select
    case SUCCESS_SUBJECT
       select case Language
         case "eng" 
	    GetErrorMessage = "Thanks for your participation in the Electronic Device Competition"
         case "chi"
            GetErrorMessage = "多謝您參加通訊博物館的電子裝置製作比賽"
         case "por"
            GetErrorMessage = "Obrigado pela sua sua participa&ccedil;&atilde;o no Concurso de Constru&ccedil;&atilde;o de Dispositivos Electr&oacute;nicos"
       end select
    case BACK_BUTTON
       select case Language
         case "eng" 
	    GetErrorMessage = "Back"
         case "chi"
            GetErrorMessage = "返回"
         case "por"
            GetErrorMessage = "Voltar"
       end select

    case UNKNOWN_ERROR
       select case Language
         case "eng" 
	    GetErrorMessage = "A system error has occurred. Please contact us by phone."
         case "chi"
            GetErrorMessage = "系統發生錯誤。 請用電話聯絡我們。"
         case "por"
            GetErrorMessage = "Um erro ocorreu no sistema. Se faz favor, contacte-nos por telefone."
       end select
  end select
  
  select case TRUE
  	case MsgNum>=MEMBERCONTACT_REQUIRED and MsgNum<=MEMBERCONTACT_REQUIRED+4
       select case Language
         case "eng" 
	        GetErrorMessage = "Please fill in the contact details of member " & (MsgNum-MEMBERCONTACT_REQUIRED)
         case "chi"
            GetErrorMessage = "請填寫成員 "& (MsgNum-MEMBERCONTACT_REQUIRED) &"的聯絡電話或電郵" 
         case "por"
            GetErrorMessage = "Por favor preencher o telefone de contacto ou endere&ccedilo de e-mail do membro " & (MsgNum-MEMBERCONTACT_REQUIRED)
       end select
   case MsgNum>=MEMBERGRADE_REQUIRED and MsgNum<=MEMBERGRADE_REQUIRED+4
       select case Language
         case "eng" 
	        GetErrorMessage = "Please fill in the grade of member " & (MsgNum-MEMBERGRADE_REQUIRED)
         case "chi"
            GetErrorMessage = "請填寫成員 "& (MsgNum-MEMBERGRADE_REQUIRED) &"的年級" 
         case "por"
            GetErrorMessage = "Por favor preencher o grau de escolaridade do membro " & (MsgNum-MEMBERGRADE_REQUIRED)
       end select
   case MsgNum>=INVALID_MEMBEREMAIL and MsgNum<=INVALID_MEMBEREMAIL+4
       select case Language
         case "eng" 
	        GetErrorMessage = "Please fill in a valid e-mail address of member " & (MsgNum-INVALID_MEMBEREMAIL)
         case "chi"
            GetErrorMessage = "請填寫成員 "& (MsgNum-INVALID_MEMBEREMAIL) &"的正確電郵地址" 
         case "por"
            GetErrorMessage = "Por favor preencher um endere&ccedil;o v&aacute;lido de e-mail do membro " & (MsgNum-INVALID_MEMBEREMAIL)
       end select
  case MsgNum>=INVALID_MEMBERTEL and MsgNum<=INVALID_MEMBERTEL+4
       select case Language
         case "eng" 
	        GetErrorMessage = "Please fill in a valid phone number of member " & (MsgNum-INVALID_MEMBERTEL)
         case "chi"
            GetErrorMessage = "請填寫成員 "& (MsgNum-INVALID_MEMBERTEL) &"的正確電話" 
         case "por"
            GetErrorMessage = "Por favor preencher um n&uacute;mero v&aacute;lido de telefone do membro " & (MsgNum-INVALID_MEMBERTEL)
       end select
  end select   

End Function

Function SendMail(HtmlBody, Subject, FromAddress, ToAddress)
  Dim myMail
  Set myMail=CreateObject("CDO.Message")
  if myMail Is Nothing Then
  	Response.Write("Cannot create CDO")
  	SendMail=False
  	Return
  end if
  myMail.Subject=Subject  
  if FromAddress="" Then
	FromAddress = Chr(34) & Request.Form("leaderEmail") & Chr(34) & " <webmaster@macao.communications.museum>"
  End If
  myMail.From=FromAddress 
  myMail.BodyPart.CharSet = "utf-8"
  myMail.To=ToAddress
  MyMail.Bcc="webmaster@macao.communications.museum"
  myMail.HtmlBody=HtmlBody
  myMail.HTMLBodyPart.Charset = "utf-8" 
  myMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = EMAIL_SERVER
  myMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
  myMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
  myMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 10
  'myMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
  'myMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername") = "info@macao.communications.museum"
  'myMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "info0621"
  myMail.Configuration.Fields.Update
  myMail.Send

  Set myMail=Nothing
  SendMail=True
End Function

Function HTMLRow(caption, fieldname)
 HTMLRow = "<tr><th valign=top align=right width=30% >" & caption & "</th><td>" & IIF(IsEmpty(fieldname),"&nbsp;",Server.HTMLEncode(Request.Form(fieldname))) & "</td></tr>" &chr(13)&chr(10)
End Function

Function GetMailBody(InternalUse)
  Dim M
  
  M = "<html xmlns="http://www.w3.org/1999/xhtml">"
  M = M & "<head><title>2010年度通訊博物館電子裝置製作比賽報名表</title><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head>"
  M = M & "<body>"
  If not InternalUse Then
	M = M & GetErrorMessage(Language, SUCCESS_MSG) & "<br><br>"
  End If
  M = M & "<table border=1 width=100% ><tr><th colspan='2'>" & _
    "<h3>2010年度通訊博物館電子裝置製作比賽報名表<br>" & _
    "Ficha de Inscri&ccedil;&atilde;o do Concurso de Constru&ccedil;&atilde;o de Dispositivos Electr&oacute;nicos</h3></th></tr>"
  If InternalUse Then
	  M = M & "<tr><th align=right>申請編號 Requerimento n.&#186;:</th><td>&nbsp;</td></tr>"
  End If
  M = M & "<tr><th align=center valign=top colspan=2>參賽學生資料 Informação dos Participantes</th></tr>"
  M = M & HTMLRow("組長中文名<br>Nome do Líder em Chinês", "leaderChineseName")
  M = M & HTMLRow("組長葡文名<br>Nome do Líder em Português", "leaderPortugueseName")  
  M = M & HTMLRow("組長聯絡電話<br>Telefone do Líder", "leaderTel")
  M = M & HTMLRow("組長聯絡電郵<br>E-mail do Líder", "leaderEmail")  
  M = M & HTMLRow("組長年級<br>Grau do Líder", "leaderGrade")

  Dim i
  for i = 1 to 3 
    if Not IsEmpty("member"&i&"ChineseName") then
      M = M & HTMLRow("成員"&i &"中文名<br>Nome do Membro "&i&" em Chin&ecirc;s", "member"&i&"ChineseName")
      M = M & HTMLRow("成員"&i &"葡文名<br>Nome do Membro "&i&" em Portugu&ecirc;s", "member"&i&"PortugueseName")  
      M = M & HTMLRow("成員"&i&"電話<br>Telefone do Membro "&i, "member"&i&"Tel")
      M = M & HTMLRow("成員"&i&"電郵<br>E-mail do Membro "&i, "member"&i&"Email")  
      M = M & HTMLRow("成員"&i&"年級<br>Grau do Membro "&i, "member"&i&"Grade")
    end if
  next
  M = M & "<tr><th align=center valign=top colspan=2>學校資料 Informa&ccedil;&atilde;o da Escola</th></tr>"
  M = M & HTMLRow("學校名稱<br>Nome da Escola", "schoolName")
  M = M & HTMLRow("指導老師姓名", "supervisorChineseName")  
  M = M & HTMLRow("Nome do Professor Supervisor", "supervisorPortugueseName")  
  M = M & HTMLRow("指導老師聯絡電話<br>Telefone do Professor Supervisor", "supervisorTel")  
  M = M & HTMLRow("指導老師聯絡電郵<br>E-mail do Professor Supervisor", "supervisorEmail")    
  M = M & "</table>"
  M = M & "</body>"
  M = M & "</html>"  
  GetMailBody = M
End Function

Function IsEmpty(fieldName)
	Dim S 
	S = Trim(Request.Form(fieldName))
	if S="" Then
		IsEmpty = True
	else
		IsEmpty = False
	End If
End Function

Function ValidateInput(Language) 
   Dim ArrivalTime, LeaveTime
   ValidateInput = ""
   if IsEmpty("schoolName") then
       ValidateInput = ValidateInput & "<li>" & GetErrorMessage(Language, SCHOOLNAME_REQUIRED)
   end if
   if IsEmpty("leaderChineseName") and IsEmpty("leaderPortugueseName") then
       ValidateInput = ValidateInput & "<li>" & GetErrorMessage(Language, LEADERNAME_REQUIRED)
   end if

   if IsEmpty("leaderTel") then
       ValidateInput = ValidateInput & "<li>" & GetErrorMessage(Language, LEADERTEL_REQUIRED)
   end if
   
   If Not IsValidPhone(Request.Form("leaderTel")) then
       ValidateInput = ValidateInput & "<li>" & GetErrorMessage(Language, INVALID_LEADERTEL)
   End if
   
   If (Not IsEmpty("supervisorTel")) and (Not IsValidPhone(Request.Form("supervisorTel"))) then
       ValidateInput = ValidateInput & "<li>" & GetErrorMessage(Language, INVALID_SUPERVISORTEL)
   End if
   
   If (Not IsEmpty("supervisorEmail")) and (Not IsValidEmail(Request.Form("supervisorEmail"))) then
       ValidateInput = ValidateInput & "<li>" & GetErrorMessage(Language, INVALID_SUPERVISOREMAIL)
   End if
   
   
   if Not IsEmpty("leaderEmail") then
   	if not IsValidEmail(Request.Form("leaderEmail")) then
     	ValidateInput = ValidateInput & "<li>" & GetErrorMessage(Language, INVALID_LEADEREMAIL)
   	end if
   end if
   
   if Request.Form("leaderGrade")="" then
       ValidateInput = ValidateInput & "<li>" & GetErrorMessage(Language, LEADERGRADE_REQUIRED)
   end if

   
   Dim i, memberChineseName, memberPortugueseName, memberTel, memberEmail, memberGrade
   for i=1 to 3
   	 memberChineseName = "member" & i & "ChineseName" 
   	 memberPortugueseName = "member" & i & "PortugueseName"
   	 memberTel = "member" & i & "Tel"
   	 memberEmail = "member" & i & "Email"   	 
   	 memberGrade = "member" & i & "Grade"
   	 if (Not IsEmpty(memberChineseName)) Or (Not IsEmpty(memberPortugueseName)) then
   	 	if IsEmpty(memberTel) and IsEmpty(memberEmail) then
	       ValidateInput = ValidateInput & "<li>" & GetErrorMessage(Language, MEMBERCONTACT_REQUIRED + i)
	    end if
   
	    if IsEmpty(memberGrade) then
	       ValidateInput = ValidateInput & "<li>" & GetErrorMessage(Language, MEMBERGRADE_REQUIRED + i)
        end if
        
        if not IsEmpty(memberEmail) then
		  	if not IsValidEmail(Request.Form(memberEmail)) then
		     	ValidateInput = ValidateInput & "<li>" & GetErrorMessage(Language, INVALID_MEMBEREMAIL + i)
		   	end if
		end if
		if not IsEmpty(memberTel) then
	        if not IsValidPhone(Request.Form(memberTel)) then
		     	ValidateInput = ValidateInput & "<li>" & GetErrorMessage(Language, INVALID_MEMBERTEL + i)
		   	end if

		end if
   	 end if	 
   next

End Function

Function setCookie(cookieName)
	If Not IsEmpty(cookieName) Then
		Response.Cookies("Applicant")(cookieName) = Server.HTMLEncode(Request.Form(cookieName))
	End If
End Function

Function setCookies()
    setCookie("schoolName")
    setCookie("supervisorChineseName")
    setCookie("supervisorPortugueseName")
    setCookie("supervisorTel")
    setCookie("supervisorEmail")
	Response.Cookies("Applicant").Expires = Date + 365
End Function

Dim InputForm 
Dim ErrorMessage
Dim Language
Dim UrlParts
Dim Subject
Dim Result

InputForm = Request.ServerVariables("HTTP_REFERER")
Language = Request.Form("Language")
if Language="" then
   Language = "eng"
End If

ErrorMessage = ValidateInput(Language)
UrlParts = split(InputForm,"?") 
if UBound(UrlParts)>0 then
   InputForm = urlParts(0)
end if

Session("ErrorMsg") = ErrorMessage


%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=utf-8">
<%
  Response.Write("<link rel='stylesheet' type='text/css' href='/" & Language & "/default.css'>")
%>
</head>
<body>
<%
setCookies()
if ErrorMessage="" then
   On Error Resume Next
   Err.Clear
		
   Subject = "2010年度通訊博物館電子裝置製作比賽報名表 - " & Request.Form("schoolName") & " - " & Request.Form("leaderChineseName") & " " & Request.Form("leaderPortugueseName") 
   Result = SendMail(GetMailBody(True), Subject, "", "info@macao.communications.museum")
   
   If Err.Number <> 0 then
	Response.Write("<p><font color='red'><b><big>" & GetErrorMessage(Language, UNKNOWN_ERROR) & "<BR><BR>" & Err.Number & "-" & Err.Description & " - " & Err.Source & "</big></b></font></p>")
	Err.Clear
   Elseif Result=True Then
    ' Response.Write(GetMailBody(False))
	Response.Write("<p><b>" & GetErrorMessage(Language, SUCCESS_MSG) & "</b></p>")
   Else 
     Response.Write("<p><font color='red'><b><big>" & GetErrorMessage(Language, UNKNOWN_ERROR) & "<BR><BR>")
   End If
   Response.Write("<p><button onclick='javascript:history.go(-1)'>" & GetErrorMessage(Language, BACK_BUTTON) & "</button></p>")
   if Not IsEmpty("leaderEmail") Then
	 ' Automatic reply
   	 Result=SendMail(GetMailBody(False), GetErrorMessage(Language, SUCCESS_SUBJECT), "info@macao.communications.museum", Request.Form("leaderEmail"))
   end if
   if Not IsEmpty("supervisorEmail") Then
	 ' Automatic reply
   	 Result=SendMail(GetMailBody(False), GetErrorMessage(Language, SUCCESS_SUBJECT), "info@macao.communications.museum", Request.Form("supervisorEmail"))
   end if
   
   On Error Goto 0
Else
   Response.Redirect InputForm & "?" & Request.Form 
end if

'if IsValidFutureDate("1/1/2007") then
'	Response.Write("OK1")
'end if

'if IsValidFutureDate("1/1/2008") then
'	Response.Write("OK2")
'end if

'if IsValidFutureDate("aa") then
'	Response.Write("OK3")
'end if

'if IsValidFutureDate("31/12/2007") then
'	Response.Write("OK4")
'end if


'if IsValidFutureDate("12/31/2007") then
'	Response.Write("OK5")
'end if


%>
</body>

</html>